﻿using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace vCrossPost
{
    public partial class FrmUserKey : Form
    {
        private readonly Predicate<string> _userKeyValidator;

        /// <summary>
        /// Gets the user key.
        /// </summary>
        /// <value>The user key.</value>
        public string UserKey
        {
            get { return txtUserKey.Text; }
        }

        public FrmUserKey(Predicate<string> userKeyValidator)
        {
            if (userKeyValidator == null) throw new ArgumentNullException("userKeyValidator");
            _userKeyValidator = userKeyValidator;

            InitializeComponent();
        }

        private void bwValidate_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = _userKeyValidator((string)e.Argument);
        }

        private void bwValidate_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (DialogResult == DialogResult.Cancel)
                return;

            var valid = (bool)e.Result;

            if (valid)
            {
                DialogResult = DialogResult.OK;
                return;
            }

            cmdOK.Enabled = true;
            pnlValidate.Visible = false;
            errProv.SetError(txtUserKey, Properties.Resources.UserKeyNotValid);
        }

        private void cmdOK_Click(object sender, EventArgs e)
        {
            cmdOK.Enabled = false;
            pnlValidate.Visible = true;
            bwValidate.RunWorkerAsync(txtUserKey.Text);
        }
    }
}